<template>
  <div>
    <!-- 面包屑组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 需要用native属性 -->
      <el-breadcrumb-item :to="{ path: '/home' }" @click.native="returnHome"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 消息提示 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 active:激活项 -->
      <el-steps
        :space="200"
        :active="activeIndex - 1"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 需要用一个form表单来接受数据，但表单只能嵌套在tbas外面 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- tabs选项卡 共用activeIndex来一起 -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeLeaveTab"
          @tab-click="tabsClicked"
        >
          <el-tab-pane label="基本信息" name="1">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <!-- 商品分类 -->
            <el-cascader
              v-model="addForm.goods_cat"
              :options="catesList"
              :props="options"
              @change="handleChange"
            ></el-cascader>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="2">
            <!-- 根据参数个数指定 再渲染参数具体属性 -->
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 属性是通过attr_vals数组渲染 -->
              <el-checkbox-group v-model="item.attr_vals">
                <!-- 直接选中便可以取消当前的属性 -->
                <el-checkbox
                  v-for="(attr, index) in item.attr_vals"
                  :key="index"
                  :label="attr"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="3">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="4">
            <!-- 使用upload组件上传图片
            现在并不成功，因为它请求时候并没有携带应有的token值
            设置请求头，携带authorization 的 token
            -->
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="5">
            <quill-editor
              v-model="addForm.goods_introduce"
              style="height: 200px; margin-bottom: 15px"
            ></quill-editor>
            <el-button type="primary" @click="addGood" style="margin-top: 60px"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <span slot="footer" class="dialog-footer">
        <img :src="preUrl" alt="" style="width: 100%" />
        <el-button @click="previewVisible = false">取 消</el-button>
        <el-button type="primary" @click="previewVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'AddGood',
  data () {
    return {
      activeIndex: '1',
      // 表单数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [], // 以id为内容的数组
        pics: [],
        goods_introduce: '', // 商品介绍
        attrs: []
      },
      addFormRules: {
        goods_name: [{
          required: true, message: '名称不能为空！', trigger: 'blur'
        }],
        goods_price: [{
          required: true, message: '请输入价格！', trigger: 'blur'
        }],
        goods_weight: [{
          required: true, message: '请输入重量！', trigger: 'blur'
        }],
        goods_number: [{
          required: true, message: '请输入商品数量！', trigger: 'blur'
        }]
      },
      catesList: [],
      // 级联选择器
      options: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      manyTableData: [], // 获取的动态商品参数列表
      onlyTableData: [],
      // 上传图片的url
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: sessionStorage.getItem('token')
      },
      previewVisible: false,
      // 预览图片的地址
      preUrl: ''
    }
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) { return this.addForm.goods_cat[2] }
      return null
    }
  },
  methods: {
    returnHome () {
      this.$bus.$emit('changePath')
    },
    // 获取分类列表
    async getCatesList () {
      const { data: res } = await this.$https.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('分类列表获取失败！')
      }
      this.catesList = res.data
    },
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // tab之间的切换的控制
    beforeLeaveTab (activeName, oldActiveName) {
      if (oldActiveName === '1' && this.addForm.goods_cat.length !== 3) {
        this.$message('请先选择分类！')
        return false
      }
      return true
    },
    // tab栏切换点击方法
    async tabsClicked () {
      if (this.activeIndex === '2') {
        const { data: res } = await this.$https.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数失败！')
        }
        // 渲染之前先将属性字符串分割为数组
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '3') {
        const { data: res } = await this.$https.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数失败！')
        }
        this.onlyTableData = res.data
      }
    },
    // 预览图片操作
    handlePreview (file) {
      this.previewVisible = true
      this.preUrl = file.response.data.url
    },
    // 移除图片操作 接收的是当前要被删除的文件的信息
    handleRemove (file) {
      // 先获取文件的临时路径
      const filePath = file.response.data.tmp_path
      // 从pisc中找出对应的下标
      const i = this.addForm.pics.findIndex(p =>
        p.pic === filePath
      )
      // 用splice方法删除对应的图片
      this.addForm.pics.splice(i, 1)
    },
    // 监听文件上传成功
    handleSuccess (res) {
      // 根据后端挨api接口文档，需要一个pics的对象数组
      const picInfo = { pic: res.data.tmp_path }
      // 每个对象中含有一个pic属性，保存当前文件的临时存放路径
      this.addForm.pics.push(picInfo)
    },
    addGood () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请完善表单信息！')
        }
        // 将选择器分类进行处理
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数和静态属性 mantabledata onlytabledata
        this.manyTableData.forEach(element => {
          const info = {
            attr_id: element.attr_id,
            attr_value: element.attr_vals.join(' ')
          }
          // 将规定格式的对象添加进入数组
          form.attrs.push(info)
        })
        this.onlyTableData.forEach(element => {
          const info = {
            attr_id: element.attr_id,
            attr_value: element.attr_vals
          }
          // 将规定格式的对象添加进入数组
          form.attrs.push(info)
        })
        const { data: res } = await this.$https.post('goods', form)
        if (res.meta.status !== 201) {
          console.log(res)
          return this.$message.error('创建商品失败！')
        }
        this.$router.push('/goods')
      })
    }
  },
  created () {
    this.getCatesList()
  }
}
</script>

<style scoped>
.el-steps {
  margin: 15px 0;
  font-size: 12px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
</style>
